package com.bigfans.userservice.api;

import com.bigfans.framework.Applications;
import com.bigfans.framework.CurrentUser;
import com.bigfans.framework.annotations.NeedLogin;
import com.bigfans.framework.web.BaseController;
import com.bigfans.framework.web.RestResponse;
import com.bigfans.userservice.model.Address;
import com.bigfans.userservice.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lichong
 * 2015年3月30日下午9:40:23
 * @Description:用户收货地址控制器
 */
@RestController
public class AddressApi extends BaseController {

    @Autowired
    private AddressService addressService;

    @NeedLogin
    @GetMapping("/myAddresses")
    public RestResponse myAddresses() throws Exception {
        CurrentUser cu = Applications.getCurrentUser();
        List<Address> addresses = addressService.listByUser(cu.getUid());
        return RestResponse.ok(addresses);
    }

    @NeedLogin
    @GetMapping(value = "/myAddress/{addressId}")
    public RestResponse myAddress(@PathVariable(name = "addressId") String addressId) throws Exception {
        CurrentUser su = Applications.getCurrentUser();
        Address loadedAddress = addressService.getUserAddress(addressId, su.getUid());
        return RestResponse.ok(loadedAddress);
    }

    @NeedLogin
    @GetMapping(value = "/address")
    public RestResponse load(@RequestParam(name = "id") String addressId) throws Exception {
        CurrentUser su = Applications.getCurrentUser();
        Address loadedAddress = addressService.getUserAddress(addressId, su.getUid());
        return RestResponse.ok(loadedAddress);
    }

    @NeedLogin
    @PostMapping(value = "/address")
    public RestResponse create(@RequestBody Address address) throws Exception {
        CurrentUser currentUser = Applications.getCurrentUser();
        address.setUserId(currentUser.getUid());
        addressService.create(address);
        return RestResponse.ok(address);
    }

    @NeedLogin
    @PostMapping(value = "/address/update")
    public RestResponse update(@RequestBody Address address) throws Exception {
        CurrentUser currentUser = Applications.getCurrentUser();
        address.setUserId(currentUser.getUid());
        addressService.update(address);
        return RestResponse.ok(address);
    }

    @NeedLogin
    @GetMapping(value = "/address/remove")
    public RestResponse remove(@RequestParam(name = "id") String addressId) throws Exception {
        CurrentUser currentUser = Applications.getCurrentUser();
        addressService.delete(currentUser.getUid(), addressId);
        return RestResponse.ok();
    }
}
